<template>
<div id="app">
    <div>
      <span>图书名称:</span>
      <input type="text" v-model.trim="bookname" @focus="isok=false" ref="books" />
    </div>
    <div>
      <button ref="mybtn"  :disabled="isok" @click="onbtn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>图书名称</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        <item @editBook="editBook" @getList="getlist"  v-for="item in list" :key="item.id" :item="item"/>

      </table>
    </div>
  </div>
</template>
<script>
import item from './components/item.vue'
let id = null
export default {
  components: { item },
  data () {
    return {
      list: [],
      bookname: '',
      isok: false
    }
  },
  created () {
    this.getlist()
  },
  methods: {
    async getlist () {
      try {
        const arr = await this.$axios({
          url: '/books'
        })
        this.list = arr.data
      } catch (err) {
        alert(err.message)
      }
    },
    // 验证图书名称是否存在
    async reviewlist () {
      try {
        const res = await this.$axios({
          url: 'books/book/' + this.bookname
        })
        if (res.data.status === 1) {
          this.isok = true
          return console.log('已存在')
        }
      } catch (error) {
        alert(error.message)
      }
    },
    // 添加图书-提交图书信息
    async addBook () {
      try {
        const res = await this.$axios({
          url: 'books',
          method: 'post',
          data: {
            name: this.bookname
          }
        })
        if (res.data.status === 200)alert('添加图书成功')
      } catch (err) {
        alert(err.message)
      }
    },
    async  onbtn () {
      if (!this.bookname) return alert('不能为空')
      if (id) {
        await this.submitBook()
      } else {
        await this.reviewlist()
        await this.addBook()
      }
      await this.getlist()
      this.bookname = ''
    },
    async editBook (i) {
      id = i
      // 编辑图书-根据ID查询图书信息
      try {
        const res = await this.$axios({
          url: '/books/' + id
        })
        this.bookname = res.data.name
        this.$refs.books.focus()
      } catch (err) {
        alert(err.message)
      }
    },
    // 编辑图书-提交图书信息
    async submitBook () {
      try {
        const res = await this.$axios({
          url: '/books/' + id,
          method: 'put',
          data: {
            name: this.bookname
          }
        })
        if (res.data.status === 200) {
          alert('编辑图书成功')
          id = null
        }
      } catch (err) {
        alert(err.message)
      }
    }

  }
}
</script>
